package com.itsu.job.components;

import cn.hutool.json.JSONUtil;
import com.itsu.job.config.JobProperties;
import com.itsu.job.exception.JobException;
import com.itsu.job.rpc.util.RpcCallUtil;
import com.itsu.job.rpc.util.RpcResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Jerry.Su
 * @Date 2022/2/7 15:33
 */
@Slf4j
public class RpcRegister implements InitializingBean {

    private final JobProperties jobProperties;


    public RpcRegister(JobProperties jobProperties) {
        this.jobProperties = jobProperties;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String rpcAdminAddress = jobProperties.getRpcAdminAddress();
        if (StringUtils.hasText(rpcAdminAddress)) {
            Pattern pattern = Pattern.compile(Const.HTTP_URL_REGEX);
            Matcher matcher = pattern.matcher(rpcAdminAddress.trim());
            if (matcher.matches()) {
                if (rpcAdminAddress.endsWith("/")) {
                    rpcAdminAddress = rpcAdminAddress.substring(0, rpcAdminAddress.length() - 1);
                }
                String requestData = JSONUtil.toJsonStr(JSONUtil.createObj().putOpt("registerAddress", getCurRegAddress()));
                RpcResult result = RpcCallUtil.call(rpcAdminAddress + Const.REGISTER_URI, requestData, jobProperties.getRpc().getAccessToken());
                if (result.getCode() == 0) {
                    log.info("rpc register success with url");
                }
            } else {
                throw new JobException("not a valid http url for job admin rpc address. [ " + rpcAdminAddress + " ]");
            }
        } else {
            log.info("Rpc Admin address is empty, will not register node for Rpc call");
        }
    }


    protected String getCurRegAddress() throws UnknownHostException {
        JobProperties.Rpc rpc = jobProperties.getRpc();
        int port = rpc.getPort();
        String address = InetAddress.getLocalHost().getHostAddress();
        return "http://" + address + ":" + port;
    }
}
